package com.rui.flyweight.model;

import com.rui.flyweight.obj.ITicket;
import com.rui.flyweight.obj.TrainTicket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author:  ZhangRui
 * @Date:    2023/3/3 13:16
 * @Version:    1.0
 */
public class TicketFactory {

    private static Map<String, ITicket> pool = new ConcurrentHashMap<>();

    public static ITicket getTicket(String from, String to) {

        String key = from + "->" + to;
        if (pool.containsKey(key)) {
            System.out.println("使用缓存获取火车票:" + key);
            return pool.get(key);
        }

        System.out.println("使用数据库获取火车票:" + key);
        ITicket ticket = new TrainTicket(from, to);
        pool.put(key, ticket);
        return ticket;
    }

}
